package org.jeecg.modules.xl.product.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.query.QueryRuleEnum;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.xl.product.entity.XlProductInfo;
import org.jeecg.modules.xl.product.entity.XlProductPics;
import org.jeecg.modules.xl.product.service.IXlProductInfoService;
import org.jeecg.modules.xl.product.service.IXlProductPicsService;
import org.jeecg.modules.xl.product.vo.XlProductInfoPage;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;


/**
* @Description: 商品主档
* @Author: jeecg-boot
* @Date:   2024-10-18
* @Version: V1.0
*/
@Api(tags="productmain")
@RestController
@RequestMapping("/xl/productmain")
@Slf4j
public class XlProductInfoMainController {
   @Autowired
   private IXlProductInfoService xlProductInfoService;
   @Autowired
   private IXlProductPicsService xlProductPicsService;
    @Value("${pichost}")
    private String baseUrl;
   /**
    * 分页列表查询
    *
    * @param xlProductInfo
    * @param pageNo
    * @param pageSize
    * @param req
    * @return
    */
   //@AutoLog(value = "xl_product_info-分页列表查询")
   @GetMapping(value = "/list")
   public Result<IPage<XlProductInfo>> queryPageList(XlProductInfo xlProductInfo,
                                                     @RequestParam(name="noIds", required=false) String noIds,
                                                     @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                                     @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                                     HttpServletRequest req) {
       // 自定义查询规则
       Map<String, QueryRuleEnum> customeRuleMap = new HashMap<>();
       // 自定义多选的查询规则为：LIKE_WITH_OR
       customeRuleMap.put("status", QueryRuleEnum.LIKE_WITH_OR);
       QueryWrapper<XlProductInfo> queryWrapper = QueryGenerator.initQueryWrapper(xlProductInfo, req.getParameterMap(),customeRuleMap);

       //过滤id集合，这段代码只用于创建订单时，商品选择
       if (StringUtils.isNotBlank(noIds)){
           queryWrapper.notIn("id", noIds.split(","));
           queryWrapper.notIn("upc_code", noIds.split(","));
       }
       Page<XlProductInfo> page = new Page<XlProductInfo>(pageNo, pageSize);
       IPage<XlProductInfo> pageList = xlProductInfoService.page(page, queryWrapper);
       if(ObjectUtil.isNotEmpty(pageList.getRecords())){
           //查询每个upccode
           String targetUpcCode = pageList.getRecords().stream().map(productInfoT -> "'" + productInfoT.getUpcCode() + "'").collect(Collectors.joining(","));
           Map<String,Map<String, String>> coverCustmoerMap = xlProductInfoService.getCoverCustomer(targetUpcCode);

           //String baseUrl = "http://47.93.163.105:8058/jeecg-boot/sys/common/static/";
           List<XlProductInfo> newRecordsList = new ArrayList<>();
           for(XlProductInfo xlProductInfoTemp : pageList.getRecords()){
               //设置coverUpcCode
               if(ObjectUtil.isNotEmpty(coverCustmoerMap)&&coverCustmoerMap.containsKey(xlProductInfoTemp.getUpcCode())){
                   xlProductInfoTemp.setCoverCustomer(coverCustmoerMap.get(xlProductInfoTemp.getUpcCode()).get("coverCustomer"));
               }
               //设置主图
               if(ObjectUtil.isNotEmpty(xlProductInfoTemp.getMainPic())) {
                   if(!xlProductInfoTemp.getMainPic().contains(baseUrl)){
                       xlProductInfoTemp.setMainPic(baseUrl + xlProductInfoTemp.getMainPic());
                   }

               }else{
                   xlProductInfoTemp.setMainPic(baseUrl+ "/temp/nophoto.png");
               }
               newRecordsList.add(xlProductInfoTemp);
           }
           pageList.setRecords(newRecordsList);
       }

       return Result.OK(pageList);
   }

   /**
    *   添加
    *
    * @param xlProductInfo
    * @return
    */
   @RequiresPermissions("org.jeecg.modules.xl:xl_product_info:add")
   @PostMapping(value = "/add")
   public Result<String> add(@RequestBody XlProductInfo xlProductInfo) {
      // XlProductInfo xlProductInfo = new XlProductInfo();
       //BeanUtils.copyProperties(xlProductInfoPage, xlProductInfo);
       xlProductInfo.setStatus("1");
       xlProductInfoService.save(xlProductInfo);//saveMain(xlProductInfo, xlProductInfoPage.getXlProductPicsList());
       return Result.OK("添加成功！");
   }

   /**
    *  编辑
    *
    * @param xlProductInfo
    * @return
    */

   @ApiOperation(value="xl_product_info-编辑", notes="xl_product_info-编辑")
   @RequiresPermissions("org.jeecg.modules.xl:xl_product_info:edit")
   @RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
   public Result<String> edit(@RequestBody XlProductInfo xlProductInfo) {
//       XlProductInfo xlProductInfo = new XlProductInfo();
//       BeanUtils.copyProperties(xlProductInfoPage, xlProductInfo);
       XlProductInfo xlProductInfoEntity = xlProductInfoService.getById(xlProductInfo.getId());
       if(xlProductInfoEntity==null) {
           return Result.error("未找到对应数据");
       }
       //String baseUrl = "http://47.93.163.105:8058/jeecg-boot/sys/common/static/";
       String tempMailPic = xlProductInfo.getMainPic();
       if(StrUtil.containsAny(tempMailPic,baseUrl)){
           String result = StrUtil.replace(tempMailPic, baseUrl, "");
           xlProductInfo.setMainPic(result);
       }
       xlProductInfoService.updateById(xlProductInfo);
       //xlProductInfoService.updateMain(xlProductInfo, xlProductInfoPage.getXlProductPicsList());
       return Result.OK("编辑成功!");
   }

   /**
    *   通过id删除
    *
    * @param id
    * @return
    */
   @AutoLog(value = "xl_product_info-通过id删除")
   @ApiOperation(value="xl_product_info-通过id删除", notes="xl_product_info-通过id删除")
   @RequiresPermissions("org.jeecg.modules.xl:xl_product_info:delete")
   @DeleteMapping(value = "/delete")
   public Result<String> delete(@RequestParam(name="id",required=true) String id) {
       xlProductInfoService.delMain(id);
       return Result.OK("删除成功!");
   }

   /**
    *  批量删除
    *
    * @param ids
    * @return
    */
   @AutoLog(value = "xl_product_info-批量删除")
   @ApiOperation(value="xl_product_info-批量删除", notes="xl_product_info-批量删除")
   @RequiresPermissions("org.jeecg.modules.xl:xl_product_info:deleteBatch")
   @DeleteMapping(value = "/deleteBatch")
   public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
       this.xlProductInfoService.delBatchMain(Arrays.asList(ids.split(",")));
       return Result.OK("批量删除成功！");
   }

   /**
    * 通过id查询
    *
    * @param id
    * @return
    */
   //@AutoLog(value = "xl_product_info-通过id查询")
   @ApiOperation(value="xl_product_info-通过id查询", notes="xl_product_info-通过id查询")
   @GetMapping(value = "/queryById")
   public Result<XlProductInfo> queryById(@RequestParam(name="id",required=true) String id) {
       XlProductInfo xlProductInfo = xlProductInfoService.getById(id);
       if(xlProductInfo==null) {
           return Result.error("未找到对应数据");
       }
       return Result.OK(xlProductInfo);

   }

   /**
    * 通过id查询
    *
    * @param id
    * @return
    */
   //@AutoLog(value = "产品图片通过主表ID查询")
   @ApiOperation(value="产品图片主表ID查询", notes="产品图片-通主表ID查询")
   @GetMapping(value = "/queryXlProductPicsByMainId")
   public Result<List<XlProductPics>> queryXlProductPicsListByMainId(@RequestParam(name="id",required=true) String id) {
       List<XlProductPics> xlProductPicsList = xlProductPicsService.selectByMainId(id);
       return Result.OK(xlProductPicsList);
   }

   /**
   * 导出excel
   *
   * @param request
   * @param xlProductInfo
   */
   @RequiresPermissions("org.jeecg.modules.xl:xl_product_info:exportXls")
   @RequestMapping(value = "/exportXls")
   public ModelAndView exportXls(HttpServletRequest request, XlProductInfo xlProductInfo) {
     // Step.1 组装查询条件查询数据
     QueryWrapper<XlProductInfo> queryWrapper = QueryGenerator.initQueryWrapper(xlProductInfo, request.getParameterMap());
     LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

     //配置选中数据查询条件
     String selections = request.getParameter("selections");
     if(oConvertUtils.isNotEmpty(selections)) {
        List<String> selectionList = Arrays.asList(selections.split(","));
        queryWrapper.in("id",selectionList);
     }
     //Step.2 获取导出数据
     List<XlProductInfo> xlProductInfoList = xlProductInfoService.list(queryWrapper);

     // Step.4 AutoPoi 导出Excel
     ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
     mv.addObject(NormalExcelConstants.FILE_NAME, "xl_product_info列表");
     mv.addObject(NormalExcelConstants.CLASS, XlProductInfo.class);
     mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("xl_product_info数据", "导出人:"+sysUser.getRealname(), "xl_product_info"));
     mv.addObject(NormalExcelConstants.DATA_LIST, xlProductInfoList);
     return mv;
   }

   /**
   * 通过excel导入数据
   *
   * @param request
   * @param response
   * @return
   */
   @RequiresPermissions("org.jeecg.modules.xl:xl_product_info:importExcel")
   @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
   public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
     MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
     Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
     for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
         // 获取上传文件对象
         MultipartFile file = entity.getValue();
         ImportParams params = new ImportParams();
         params.setTitleRows(2);
         params.setHeadRows(1);
         params.setSheetNum(1);	//只导入一个sheet数据
         params.setStartSheetIndex(0);	//从第一个sheet开始导入
         params.setNeedSave(false);
         try {
             List<XlProductInfo> list = ExcelImportUtil.importExcel(file.getInputStream(), XlProductInfo.class, params);
             // 输出分组结果
             for (XlProductInfo po : list) {
                 po.setStatus("1");
                 xlProductInfoService.save(po);
             }
             return Result.OK("文件导入成功！数据行数:" + list.size());
         } catch (Exception e) {
             log.error(e.getMessage(),e);
             return Result.error("文件导入失败:"+e.getMessage());
         } finally {
             try {
                 file.getInputStream().close();
             } catch (IOException e) {
                 e.printStackTrace();
             }
         }
     }
     return Result.OK("文件导入失败！");
   }

}
